package util;

import java.io.*;

public class FileWork {
	
	public static FileWork getInstance() {
	      return INSTANCE;
	}
	
    public Boolean createFile(String path) {
    	try {
    		File file = new File(path);
    		// Create file if it does not exist
    		boolean success = file.createNewFile();
    		return success;    		
        } catch (IOException e) {
        	System.err.println("Error: " + e.getMessage());
        	return false;
        }
    }
    
	public Boolean writeFile(String path, String text) {
		try {
			Writer output = null;
			File file = new File(path);
			output = new BufferedWriter(new FileWriter(file));
			output.write(text);
			output.close();
			return true;
		} catch (IOException e) {
			System.err.println("Error: " + e.getMessage());
			return false;
		}
    }
    
	public Boolean saveBase64ToPNG(String path, String base64) {
		try {
			byte decoded[] = new sun.misc.BASE64Decoder().decodeBuffer(base64);
			FileOutputStream  fos = null;
			fos = new FileOutputStream(path);
			fos.write(decoded);
			fos.close();

			return true;
		} catch (IOException e) {
			System.err.println("Error: " + e.getMessage());
			return false;
		}
    }
	
    public void appendFile(String path, String text) {
        try {
            // Create file 
            FileWriter fstream = new FileWriter(path,true);
            BufferedWriter out = new BufferedWriter(fstream);
            out.write(text);
            //Close the output stream
            out.close();
        } catch(Exception e){//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
    }
    
    public String readFile(String path) {
    	String result = "";
    	try {
    		// Open the file that is the first 
    		// command line parameter
    		FileInputStream fstream = new FileInputStream(path);
        	// Get the object of DataInputStream
        	DataInputStream in = new DataInputStream(fstream);
        	BufferedReader br = new BufferedReader(new InputStreamReader(in));
        	String strLine;
        	//Read File Line By Line
        	while ((strLine = br.readLine()) != null) {
        		result = result.concat(strLine) + "\n";
        	}
        	//Close the input stream
        	in.close();
         
        } catch (Exception e) {
        		//Catch exception if any
        		System.err.println("Error: " + e.getMessage());
        }
        	return result;
	}
    
    public Boolean deleteFileOrDir(String path) {
        File f1 = new File(path);
        boolean success = f1.delete();
        if (!success) {
        	System.exit(0);
        	return true;
        } else {
        	return false;
        }
    }
    
    public Boolean createDir(String path) {
    	Boolean result = false;
    	try {
    		// Create one directory
    		Boolean success = (new File(path)).mkdir();
    		if (success) {
    			result = true;
    		}    
    	} catch (Exception e) {
    		//Catch exception if any
    		System.err.println("Error: " + e.getMessage());
    	}
    	return result;
   	}
    
    public Boolean createDirs(String path) {
    	Boolean result = true;
    	try {
    		// Create multiple directories
    		//boolean success = (new File(path)).mkdir();    		
    		(new File(path)).mkdirs();
    	} catch(Exception e) {
    		//Catch exception if any
    		System.err.println("Error: " + e.getMessage());
    		result = false;
    	}
    	return result;
   	}
    
    /*public Boolean copyFile(String srFile, String dtFile){
    	Boolean result = true;
        try{
          File f1 = new File(srFile);
          File f2 = new File(dtFile);
          InputStream in = new FileInputStream(f1);
          OutputStream out = new FileOutputStream(f2);

          byte[] buf = new byte[1024];
          int len;
          while ((len = in.read(buf)) > 0){
            out.write(buf, 0, len);
          }
          in.close();
          out.close();
        }
        catch(FileNotFoundException ex){
          System.err.println(ex.getMessage() + " in the specified directory.");
          result = false;
        }
        catch(IOException e){
          System.err.println(e.getMessage());
          result = false;
        }
        return result;
        
      }
    */
    
    
    public void copy(String fromFileName, String toFileName) throws IOException {
        File fromFile = new File(fromFileName);
        File toFile = new File(toFileName);

        if (!fromFile.exists())
   	      throw new IOException("FileCopy: " + "no such source file: " + fromFileName);
    	   if (!fromFile.isFile())
    	     throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName);
    	   if (!fromFile.canRead())
    	     throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName);

    	   if (toFile.isDirectory())
    	      toFile = new File(toFile, fromFile.getName());

    	   if (toFile.exists()) {
    	     if (!toFile.canWrite())
    	      throw new IOException("FileCopy: destination file is unwriteable: " + toFileName);
    	      System.err.print("Overwrite existing file " + toFile.getName() + "? (Y/N): ");
    	      System.err.flush();
    	      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    	      String response = in.readLine();
    	      if (!response.equals("Y") && !response.equals("y"))
    	        throw new IOException("FileCopy: existing file was not overwritten.");
    	   } else {
    	      String parent = toFile.getParent();
    	      if (parent == null)
    	        parent = System.getProperty("user.dir");
    	      	File dir = new File(parent);
    	      if (!dir.exists())
    	        throw new IOException("FileCopy: destination directory doesn't exist: " + parent);
    	      if (dir.isFile())
    	        throw new IOException("FileCopy: destination is not a directory: " + parent);
    	      if (!dir.canWrite())
    	        throw new IOException("FileCopy: destination directory is unwriteable: " + parent);
    	   }

    	   FileInputStream from = null;
    	    FileOutputStream to = null;
    	    try {
    	      from = new FileInputStream(fromFile);
    	      to = new FileOutputStream(toFile);
    	      byte[] buffer = new byte[4096];
    	      int bytesRead;

    	      while ((bytesRead = from.read(buffer)) != -1)
    	        to.write(buffer, 0, bytesRead); // write
    	    } finally {
    	      if (from != null)
    	        try {
    	          from.close();
    	        } catch (IOException e) {
    	          ;
    	        }
    	      if (to != null)
    	        try {
    	          to.close();
    	        } catch (IOException e) {
    	          ;
    	        }
        }
    }
    	
    public Boolean existsFileOrDir(String path) {
        File f1 = new File(path);
        if(f1.exists()) {
            return true;
        } else {
        	return false;
        }
   }
    
      
    private static final FileWork INSTANCE = new FileWork();
}